const Koa = require('koa')
const KoaRouter = require('@koa/router')
const {
  koaBody
} = require('koa-body')
const fs = require('fs')
const path = require('path')
const koaStatic = require('koa-static')
const OSS = require('ali-oss')
const app = new Koa();
const router = new KoaRouter();


 
app.use(koaBody({
  // 开启文件处理
  multipart: true
}))
app.use(koaStatic(path.resolve(__dirname, 'public/uploadFiles')))
app
  .use(router.routes())
  .use(router.allowedMethods());

app.listen(1234, () => console.log(1234));


router.post('/upload/koa', ctx => {
  // 1. 获取发送过来的文件名称和存储路径
  const {
    originalFilename,
    filepath
  } = ctx.request.files.file
  // 2. 移动到指定位置
  fs.copyFileSync(
    filepath,
    path.resolve(__dirname, 'public', 'uploadFiles', originalFilename)
  )
  // 3. 返回文件上传存储的服务器路径
  ctx.body = {
    code: 200,
    data: `http://localhost:1234/${originalFilename}`
  }
})

router.get('/upload/list', ctx => {
  ctx.body = {
    code: 200,
    data: fs.readdirSync(path.resolve(__dirname, 'public/uploadFiles')).map(v => {
      return `http://localhost:1234/${v}`
    })
  }
})

router.delete('/upload/:name', ctx => {
  const {
    name
  } = ctx.request.params;

  const pathname = path.resolve(__dirname, 'public', 'uploadFiles', name)
  if (fs.existsSync(pathname))
    fs.unlinkSync(pathname)

  ctx.body = {
    code: 200,
  }
})


/******************************** 云服务器 ****************************************/

const client = new OSS({
  // yourregion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
  region: 'oss-cn-shanghai',
  // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
  accessKeyId: 'LTAI5tMwC9kaobjiZ5SnTQLh',
  accessKeySecret: 'i3vFn1LoEg5h9UmeVbL4EdIwSceCD7',
  // 填写Bucket名称。
  bucket: '76543',
});

router.post('/upload/ali/oss',async  ctx => {
  // 1. 获取文件路径和名称
  const {
    originalFilename,
    filepath
  } = ctx.request.files.file
  // 2.上传云oss
  const result = await client.put(originalFilename, filepath)

  ctx.body = {
    code: 200,
    data: result
  }
})


router.get('/upload/ali/oss/list',async  ctx => {
  const result = await client.list()
  ctx.body = {
    code: 200,
    data: result
  }
})




router.delete('/upload/ali/oss/:name',async  ctx => {
  const { name } = ctx.request.params
  const result = await client.delete(name)
  ctx.body = {
    code: 200,
    data: result
  }
})